from pyecharts.charts import Bar, Grid, Radar
from pyecharts.charts import Scatter
import pandas as pd

from jinja2 import Markup, Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig, ThemeType
# 初始化pyecharts
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates/pyecharts"))
from pyecharts import options as opts


# 工具 移除memory中的单位 GB
def remove_GB(l: list) -> list:
    ll = []
    for x in l:
        y = int(x.replace("GB", ""))  # 去除逗号
        ll.append(y)
    return ll


# 单个cpu的散点图 响应html中的数据请求，显示pyechart
def scatter_bar(cpu_name) -> Bar:  # -> 表示要返回的是类型
    # 读取数据
    # data = pd.read_csv("data/ods/ods_cpu2006_fprate.csv")
    from dw.dw import DwUtil
    dw = DwUtil()
    sql1 = "select * from dw_cpu2017_intrate where processor = \'" + cpu_name + "\'"
    df1 = dw.execute_sql(sql1)
    data1 = df1.iloc[:, :-1]
    data1 = data1.dropna(subset=['result', 'num_core', 'memory']) # 删除缺失值
    data1 = data1[data1['result'] != 0] # 删除0值

    sql2 = "select * from dw_cpu2017_intspeed where processor = \'" + cpu_name + "\'"
    df2 = dw.execute_sql(sql2)
    data2 = df2.iloc[:, :-1]
    data2 = data2.dropna(subset=['result', 'num_core', 'memory'])  # 删除缺失值
    data2 = data2[data2['result'] != 0]  # 删除0值
    # 按CPU型号分组
    option_processor1 = data1.sort_values(by='num_core')
    core = (option_processor1['num_core']).values.tolist()
    base1 = (option_processor1['result']).values.tolist()
    option_processor2 = data2.sort_values(by='memory')
    mem = remove_GB((option_processor2['memory']).values.tolist())
    base2 = (option_processor2['result']).values.tolist()

    # print(core)
    # print(base1)
    # print(mem)
    # print(base2)
    sca1 = (
        Scatter(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)) # 主题 可修改
            .add_xaxis(core)
            # .add_xaxis([32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
            #             32, 32, 32, 32, 32, 32, 32, 32, 64, 64, 64, 64, 64, 64, 64, 64, 128, 128])
            .add_yaxis(
            series_name=cpu_name,
            y_axis=base1,
            # y_axis=[1200, 1190, 1180, 1150, 1150, 1180, 1160, 1170, 1170, 1170,
            #         0, 0, 0, 0, 1190, 1190, 1140, 0, 0, 1180, 1160, 2290, 2290, 2350,
            #         2370, 0, 2330, 2350, 2340, 0, 4660],
            symbol_size=15,
            label_opts=opts.LabelOpts(is_show=False)
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="处理器核数和测试结果关系的散点图",
                subtitle=cpu_name,
                # 标题左右位置：pos_left,pos_right，距离图表左侧/右侧距离
                # 值可以是像素值如20，也可以是相对值'20%'，或者'left'、'center'、'right'
                # pos_left='20%',

                # 标题上下位置：pos_top,pos_bottom，距离图表左侧/右侧距离
                # 值可以是像素值、相对值，或者'top'、'middle'、'bottom'
                # pos_top=20,

                # 主副标题间距，默认10
                # item_gap=20,
            ),
            xaxis_opts=opts.AxisOpts(
                type_="value",
                splitline_opts=opts.SplitLineOpts(is_show=True),
                name="核数",
            ),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                name="结果",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            tooltip_opts=opts.TooltipOpts(is_show=True),
            # visualmap_opts=opts.VisualMapOpts(type_="size", max_=10, min_=10),
            legend_opts=opts.LegendOpts(
                # 是否显示图例组件
                is_show=True,
                # 图例位置，配置方法与标题相同
                pos_left='50%',
                pos_top='8%',
                # 图例布局朝向：'horizontal'(默认，横排), 'vertical'(竖排)
                orient='vertical',
                # 对齐方式：`auto`, `left`, `right`
                align='auto',
                # 图例中每项的间隔，默认10
                item_gap=20,
                # 图例宽度和高度，默认为25和14
                # item_width=50,
                # item_height=20
            )
        )
        .set_series_opts()
    )

    sca2 = (
        Scatter(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))  # 主题 可修改
            .add_xaxis(mem)
            # .add_xaxis([32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
            #             32, 32, 32, 32, 32, 32, 32, 32, 64, 64, 64, 64, 64, 64, 64, 64, 128, 128])
            .add_yaxis(
            series_name=cpu_name,
            y_axis=base2,
            # y_axis=[1200, 1190, 1180, 1150, 1150, 1180, 1160, 1170, 1170, 1170,
            #         0, 0, 0, 0, 1190, 1190, 1140, 0, 0, 1180, 1160, 2290, 2290, 2350,
            #         2370, 0, 2330, 2350, 2340, 0, 4660],
            symbol_size=15,
            label_opts=opts.LabelOpts(is_show=False)
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(
                title="内存和测试结果关系的散点图",
                subtitle=cpu_name,
                # 标题左右位置：pos_left,pos_right，距离图表左侧/右侧距离
                # 值可以是像素值如20，也可以是相对值'20%'，或者'left'、'center'、'right'
                # pos_left='20%',

                # 标题上下位置：pos_top,pos_bottom，距离图表左侧/右侧距离
                # 值可以是像素值、相对值，或者'top'、'middle'、'bottom'
                pos_top="50%",

                # 主副标题间距，默认10
                # item_gap=20,
            ),
            xaxis_opts=opts.AxisOpts(
                type_="value",
                splitline_opts=opts.SplitLineOpts(is_show=True),
                name="内存(GB)"
            ),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                name="结果",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            tooltip_opts=opts.TooltipOpts(is_show=True),
            # visualmap_opts=opts.VisualMapOpts(type_="size", max_=10, min_=10),
            legend_opts=opts.LegendOpts(
                # 是否显示图例组件
                is_show=True,
                # 图例位置，配置方法与标题相同
                pos_left='50%',
                pos_top='60%',
                # 图例布局朝向：'horizontal'(默认，横排), 'vertical'(竖排)
                orient='vertical',
                # 对齐方式：`auto`, `left`, `right`
                align='auto',
                # 图例中每项的间隔，默认10
                item_gap=20,
                # 图例宽度和高度，默认为25和14
                # item_width=50,
                # item_height=20
            )
        )
            .set_series_opts()
    )
    # 把上面生成的两个图放进grid中并通过pos_top，pos_bottom, pos_left, pos_right设置其位置
    grid = (
        Grid()
            .add(sca1, grid_opts=opts.GridOpts(pos_top='15%', pos_bottom="55%"))
            .add(sca2, grid_opts=opts.GridOpts(pos_top='65%', pos_bottom="5%"))
    )
    return grid

def grade_bar(processor_name) -> Bar:
    from dw.dw import DwUtil
    dw = DwUtil()
    data = dw.execute_sql("SELECT * FROM processor_result WHERE processor = '{name}'".format(name=processor_name))
    gardes_name = ["整数运算性能", "浮点运算性能", "单核性能", "多核性能", "java性能", "power性能"]
    grades = data[
        ["int_grade", "float_grade", "single_grade", "multi_grade", "java_grade", "power_grade"]]
    grades = grades.replace("A", 6)
    grades = grades.replace("B", 5)
    grades = grades.replace("C", 4)
    grades = grades.replace("D", 3)
    grades = grades.replace("E", 2)
    grades = grades.replace("F", 1)
    grades = grades.replace("-", 0)
    grades = grades.values
    # print(grades)
    # print(grades.tolist())

    # v1 = [[4300, 10000, 28000, 35000, 50000, 19000]]
    # v2 = [[3, 3, 2, 5, 0, 0, 4]]
    c = (
        Radar()
            .add_schema(
            schema=[
                opts.RadarIndicatorItem(name=gardes_name[0], max_=6),
                opts.RadarIndicatorItem(name=gardes_name[1], max_=6),
                opts.RadarIndicatorItem(name=gardes_name[2], max_=6),
                opts.RadarIndicatorItem(name=gardes_name[3], max_=6),
                opts.RadarIndicatorItem(name=gardes_name[4], max_=6),
                opts.RadarIndicatorItem(name=gardes_name[5], max_=6),
                # opts.RadarIndicatorItem(name="市场", max_=25000),
            ],
            shape="circle",
            center=["50%", "50%"],
            radius="80%",
            angleaxis_opts=opts.AngleAxisOpts(
                min_=0,
                max_=360,
                is_clockwise=False,
                interval=6,
                axistick_opts=opts.AxisTickOpts(is_show=False),
                axislabel_opts=opts.LabelOpts(is_show=False),
                axisline_opts=opts.AxisLineOpts(is_show=False),
                splitline_opts=opts.SplitLineOpts(is_show=False),
            ),
            radiusaxis_opts=opts.RadiusAxisOpts(
                min_=0,
                max_=6,
                interval=1,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
                axislabel_opts=opts.LabelOpts(is_show=False),
            ),
            polar_opts=opts.PolarOpts(),
            splitarea_opt=opts.SplitAreaOpts(is_show=False),
            splitline_opt=opts.SplitLineOpts(is_show=False),
        )
            .add(
            series_name=processor_name,
            data = grades.tolist())
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(
            legend_opts=opts.LegendOpts(selected_mode="single", align='right', pos_right="20%"),
            title_opts=opts.TitleOpts(title=processor_name),
        )
    )
    return c

    # "id"
    # "processor"
    # "int_grade"
    # "float_grade"
    # "single_grade"
    # "multi_grade"
    # "java_grade"
    # "power_grade"
    # "overall_grade"
